/*
 * @Date: 2025-09-02 22:48:48
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-10-29 20:48:57
 * @FilePath: /admin-vue/src/composables/system/useUser.ts
 */
import { http } from '@/plugins/axios'

export default () => {
  const loading = ref(false)
  const collection = ref<ResponsePageResult<UserModel>>()
  const params = ref({
    key: '',
    page: 1,
    per_page: 15,
  })
  const model = ref<UserModel>()

  const load = async () => {
    loading.value = true
    collection.value = await http.request<UserModel[], ResponsePageResult<UserModel>>({
      url: `user`,
      params: params.value,
    })
    loading.value = false
  }

  const find = async (id: number) => {
    const { data } = await http.request<UserModel>({
      url: `user/${id}`,
    })
    return data
  }

  const add = async (model: UserModel) => {
    const data = await http.request<string, ResponseResult<string>>({
      url: 'user',
      method: 'POST',
      data: model,
    })
    return data
  }

  const update = async (model: UserModel) => {
    const data = await http.request<string, ResponseResult<string>>({
      url: `user/${model.id}`,
      method: 'PUT',
      data: model,
    })
    return data
  }

  const del = async (id: any) => {
    await http.request({ url: `user/${id}`, method: 'DELETE' })
    load()
  }

  const userRoles = async (id: number) => {
    const { data } = await http.request<number[]>({
      url: `user/${id}/roles`,
      data: model,
    })
    return data
  }

  const syncUserRoles = async (id: number, roles: number[]) => {
    const data = await http.request({
      url: `user/${id}/roles`,
      method: 'POST',
      data: { roles },
    })
    return data
  }

  return {
    loading,
    collection,
    model,
    load,
    params,
    find,
    add,
    update,
    del,
    userRoles,
    syncUserRoles,
  }
}
